package com.yuanqi.controller;

import com.yuanqi.domain.RetailReturnOrder;
import com.yuanqi.service.RetailReturnOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 零售退货订单控制器
 */
@RestController
@RequestMapping("/api/retail/returns")
@CrossOrigin(origins = "*")
public class RetailReturnOrderController {
    
    @Autowired
    private RetailReturnOrderService retailReturnOrderService;
    
    /**
     * 创建退货订单
     */
    @PostMapping
    public ResponseEntity<RetailReturnOrder> createReturnOrder(@RequestBody RetailReturnOrder returnOrder) {
        try {
            RetailReturnOrder createdOrder = retailReturnOrderService.createReturnOrder(returnOrder);
            return ResponseEntity.ok(createdOrder);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 更新退货订单
     */
    @PutMapping("/{id}")
    public ResponseEntity<RetailReturnOrder> updateReturnOrder(@PathVariable Long id, @RequestBody RetailReturnOrder returnOrder) {
        try {
            returnOrder.setId(id);
            RetailReturnOrder updatedOrder = retailReturnOrderService.updateReturnOrder(returnOrder);
            return ResponseEntity.ok(updatedOrder);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 根据ID查找退货订单
     */
    @GetMapping("/{id}")
    public ResponseEntity<RetailReturnOrder> getReturnOrder(@PathVariable Long id) {
        Optional<RetailReturnOrder> returnOrder = retailReturnOrderService.findById(id);
        return returnOrder.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 根据退货单编码查找退货订单
     */
    @GetMapping("/by-code/{returnCode}")
    public ResponseEntity<RetailReturnOrder> getReturnOrderByCode(@PathVariable String returnCode) {
        Optional<RetailReturnOrder> returnOrder = retailReturnOrderService.findByReturnCode(returnCode);
        return returnOrder.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 分页查找退货订单
     */
    @GetMapping
    public ResponseEntity<Page<RetailReturnOrder>> getReturnOrders(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<RetailReturnOrder> returnOrders = retailReturnOrderService.findAll(pageable);
        return ResponseEntity.ok(returnOrders);
    }
    
    /**
     * 根据原订单ID查找退货订单
     */
    @GetMapping("/original-order/{originalOrderId}")
    public ResponseEntity<List<RetailReturnOrder>> getReturnOrdersByOriginalOrderId(@PathVariable Long originalOrderId) {
        List<RetailReturnOrder> returnOrders = retailReturnOrderService.findByOriginalOrderId(originalOrderId);
        return ResponseEntity.ok(returnOrders);
    }
    
    /**
     * 根据原订单编码查找退货订单
     */
    @GetMapping("/original-order-code/{originalOrderCode}")
    public ResponseEntity<List<RetailReturnOrder>> getReturnOrdersByOriginalOrderCode(@PathVariable String originalOrderCode) {
        List<RetailReturnOrder> returnOrders = retailReturnOrderService.findByOriginalOrderCode(originalOrderCode);
        return ResponseEntity.ok(returnOrders);
    }
    
    /**
     * 根据客户ID查找退货订单
     */
    @GetMapping("/customer/{customerId}")
    public ResponseEntity<List<RetailReturnOrder>> getReturnOrdersByCustomerId(@PathVariable Long customerId) {
        List<RetailReturnOrder> returnOrders = retailReturnOrderService.findByCustomerId(customerId);
        return ResponseEntity.ok(returnOrders);
    }
    
    /**
     * 根据客户姓名查找退货订单
     */
    @GetMapping("/customer/name/{customerName}")
    public ResponseEntity<List<RetailReturnOrder>> getReturnOrdersByCustomerName(@PathVariable String customerName) {
        List<RetailReturnOrder> returnOrders = retailReturnOrderService.findByCustomerName(customerName);
        return ResponseEntity.ok(returnOrders);
    }
    
    /**
     * 根据客户电话查找退货订单
     */
    @GetMapping("/customer/phone/{customerPhone}")
    public ResponseEntity<List<RetailReturnOrder>> getReturnOrdersByCustomerPhone(@PathVariable String customerPhone) {
        List<RetailReturnOrder> returnOrders = retailReturnOrderService.findByCustomerPhone(customerPhone);
        return ResponseEntity.ok(returnOrders);
    }
    
    /**
     * 根据退货状态查找退货订单
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<List<RetailReturnOrder>> getReturnOrdersByStatus(@PathVariable String status) {
        List<RetailReturnOrder> returnOrders = retailReturnOrderService.findByReturnStatus(status);
        return ResponseEntity.ok(returnOrders);
    }
    
    /**
     * 根据日期范围查找退货订单
     */
    @GetMapping("/date-range")
    public ResponseEntity<List<RetailReturnOrder>> getReturnOrdersByDateRange(
            @RequestParam String startDate,
            @RequestParam String endDate) {
        try {
            LocalDateTime start = LocalDateTime.parse(startDate + "T00:00:00");
            LocalDateTime end = LocalDateTime.parse(endDate + "T23:59:59");
            List<RetailReturnOrder> returnOrders = retailReturnOrderService.findByReturnDateBetween(start, end);
            return ResponseEntity.ok(returnOrders);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 审核退货订单
     */
    @PostMapping("/{id}/approve")
    public ResponseEntity<RetailReturnOrder> approveReturnOrder(
            @PathVariable Long id,
            @RequestParam(defaultValue = "系统") String approverName,
            @RequestParam(required = false) String remark) {
        try {
            RetailReturnOrder returnOrder = retailReturnOrderService.approveReturnOrder(id, approverName, remark);
            return ResponseEntity.ok(returnOrder);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 拒绝退货订单
     */
    @PostMapping("/{id}/reject")
    public ResponseEntity<RetailReturnOrder> rejectReturnOrder(
            @PathVariable Long id,
            @RequestParam String reason,
            @RequestParam(defaultValue = "系统") String approverName) {
        try {
            RetailReturnOrder returnOrder = retailReturnOrderService.rejectReturnOrder(id, reason, approverName);
            return ResponseEntity.ok(returnOrder);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 处理退货订单
     */
    @PostMapping("/{id}/process")
    public ResponseEntity<RetailReturnOrder> processReturnOrder(
            @PathVariable Long id,
            @RequestParam(defaultValue = "系统") String processorName) {
        try {
            RetailReturnOrder returnOrder = retailReturnOrderService.processReturnOrder(id, processorName);
            return ResponseEntity.ok(returnOrder);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 完成退货订单
     */
    @PostMapping("/{id}/complete")
    public ResponseEntity<RetailReturnOrder> completeReturnOrder(
            @PathVariable Long id,
            @RequestParam(defaultValue = "系统") String processorName) {
        try {
            RetailReturnOrder returnOrder = retailReturnOrderService.completeReturnOrder(id, processorName);
            return ResponseEntity.ok(returnOrder);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 更新退货状态
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<RetailReturnOrder> updateReturnStatus(
            @PathVariable Long id,
            @RequestParam String status,
            @RequestParam(defaultValue = "系统") String operatorName) {
        try {
            RetailReturnOrder returnOrder = retailReturnOrderService.updateReturnStatus(id, status, operatorName);
            return ResponseEntity.ok(returnOrder);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 删除退货订单
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteReturnOrder(@PathVariable Long id) {
        try {
            retailReturnOrderService.deleteById(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 获取退货统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Object> getReturnStatistics() {
        Object statistics = retailReturnOrderService.getReturnStatistics();
        return ResponseEntity.ok(statistics);
    }
    
    /**
     * 生成退货单编码
     */
    @GetMapping("/generate-code")
    public ResponseEntity<String> generateReturnCode() {
        String returnCode = retailReturnOrderService.generateReturnCode();
        return ResponseEntity.ok(returnCode);
    }
}
